import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Pagination, Table, Button } from 'antd';
import PropTypes from 'prop-types';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import moment from 'moment';
import WarningDetail from '../warningDetail';
import * as G from '@/utils/common';
import { getDicByKey, getDictOptionsByCode } from '@/support/common';

// 电池故障预警查询
const mapStateToProps = (state: any) => ({
  batteryFaultWarning: state.batteryFaultWarning,
  loading: state.loading.models["batteryFaultWarning"],
  // loading: state.loading.effects['burningVehicle/postFetchPage'],
})
class BatteryFaultWarning extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.any
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      brandList: [], // 品牌
      seriesList: [], //  车系
      vehicleTypeList: [],  //  车型
      detailFlag: 'warning',
      currentDetailCode: '',
      detailModalVisible: '', //  详情弹框
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'batteryFaultWarning/getFetchPage',
      payload: { 
        url: '/battery/monitor/warning/page',
        ...formValues,
      },
    });
    this.getBrandData()
  }

  //  获取品牌数据列表
  getBrandData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'batteryFaultWarning/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            brandList: res.data.map((item: any) => ({
              label: item.brandName,
              value: item.brandCode
            })),
            seriesList: [],
            vehicleTypeList: [],
          })
        }
      }
    })
  }

  //  获取车系数据列表
  getSeriesData = (t: any) => {
    const { dispatch } = this.props;
    const brandId = this.searchForm.current.getFieldValue('brandCode')
    //  重置车系、车型
    this.searchForm.current.resetFields(['seriesCode', 'typeCode']);
    this.setState({
      seriesList: [],
      vehicleTypeList: [],
    })
    brandId && dispatch({
      type: 'batteryFaultWarning/getDataWithRes',
      payload: {
        url: '/common/vehicle/getserieslist',
        brandId,
      },
      callback: (res: any) => {
        this.setState({
          seriesList: res.data.map((item: any) => ({
            label: item.name,
            value: item.code,
          })),
        });
      },
    })
  }

  //  获取车型数据列表
  getVehicleTypeData = (t: any) => {
    const { dispatch } = this.props;
    this.setState({ vehicleTypeList: [] });
    this.searchForm.current.resetFields(['typeCode']);
    const brandId = this.searchForm.current.getFieldValue('brandCode');
    const seriesId = this.searchForm.current.getFieldValue('seriesCode');
    brandId && seriesId && 
      dispatch({
        type: 'batteryFaultWarning/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId,
          seriesId,
        },
        callback: (res: any) => {
          this.setState({
            vehicleTypeList: res.data.map((item: any) => ({
              label: item.name,
              value: item.code,
            })),
          });
        }
      })
  }

  handleFormReset = (fields: any) => {
    this.setState({
      formValues: {},
      seriesList: [],
      vehicleTypeList: [],
    })
  }

  dataFormat = (fields: any) => {
    if (G.isNotEmptyAndNil(fields['beginDate'])) {
      fields['beginDate'] = moment(fields.beginDate).format('YYYY-MM-DD HH:mm:ss');
    }
    if (G.isNotEmptyAndNil(fields['endDate'])) {
      fields['endDate'] = moment(fields.endDate).format('YYYY-MM-DD HH:mm:ss');
    }
    return {...fields};
  };
  
  //  详情弹框（打开）
  openDetailModal = (record: any) => {
    this.setState({
      currentDetailCode: record.code,
      detailModalVisible: true,
    })
  }

  //  详情弹框（关闭）
  closeDetailModal = () => {
    this.setState({
      currentDetailCode: '',
      detailModalVisible: false,
    });
  }

  render() {
    const { batteryFaultWarning: {
      pageData: { list, pagination },
    }, loading, location: { pathname = '/' } } = this.props
    const { formValues, brandList, seriesList, vehicleTypeList, detailFlag, currentDetailCode, detailModalVisible } = this.state;
    const faultType = getDictOptionsByCode(this.context.dicData, 'faultType');

    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    }

    const searchItems = [
      {
        title: '品牌',
        type: 'select',
        selectOptions: brandList,
        onChange: (e: any) => {
          this.getSeriesData(e)
        },
        keyValue: ['value', 'label'],
        key: 'brandCode'
      },
      {
        title: '车系',
        type: 'select',
        selectOptions: seriesList,
        onChange: (e: any) => {
          this.getVehicleTypeData(e)
        },
        keyValue: ['value', 'label'],
        key: 'seriesCode'
      },
      {
        title: '车型',
        type: 'select',
        selectOptions: vehicleTypeList,
        key: 'typeCode'
      },
      {
        title: 'VIN',
        type: 'input',
        key: 'vin',
        maxLength: 18,
      },
      {
        title: '风险等级',
        type: 'select',
        selectOptions: [
          {
            label: '低',
            value: 0
          },
          {
            label: '中',
            value: 1
          },
          {
            label: '高',
            value: 2
          },
        ],
        key: 'level',
      },
      {
        title: '故障预警类型',
        type: 'select',
        selectOptions: faultType || [],
        key: 'type',
      },
      {
        title: '处理状态',
        type: 'select',
        selectOptions: [
          {
            label: '未处理',
            value: 0
          },
          {
            label: '处理中',
            value: 1
          },
          {
            label: '已处理',
            value: 2
          },
        ],
        key: 'status',
      },


      {
        title: '预警日期起',
        type: 'datePicker',
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        key: 'beginDate',
      },
      {
        title: '预警日期止',
        type: 'datePicker',
        showTime: true,
        format: 'YYYY-MM-DD HH:mm:ss',
        key: 'endDate',
      },
    ]

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => (
        <span>共&nbsp;{page?.total}&nbsp;条</span>
      ),
    }

    const columns = [
      {
        title: '预警编号',
        dataIndex: 'code',
      },
      {
        title: '品牌',
        dataIndex: 'brandName',
      },
      {
        title: '车系',
        dataIndex: 'seriesName',
      },
      {
        title: '车型',
        dataIndex: 'typeName',
      },
      {
        title: 'VIN码',
        dataIndex: 'vin',
      },
      {
        title: '电池类型',
        dataIndex: 'batteryType',
      },
      {
        title: '电池供应商',
        dataIndex: 'batterySupplier',
      },
      {
        title: '电池包编号',
        dataIndex: 'batteryCode',
      },
      {
        title: '交付日期',
        dataIndex: 'enrollDate',
      },
      {
        title: '累计里程',
        dataIndex: 'accruedMiles',
      },
      {
        title: '风险等级',
        dataIndex: 'level',
        render: (text: any, record: any) => {
          return text == 0 ? '低' : text == 1 ? '中' : text == 2 ? '高' : '';
        }
      },
      {
        title: '预警时间',
        dataIndex: 'warningDate',
      },
      {
        title: '故障预警类型',
        dataIndex: 'type',
        render: (text: any) => {
          return getDicByKey(this.context.dicData, 'faultType', text + '');
        }
      },
      {
        title: '处理时间',
        dataIndex: 'handleDate',
      },
      {
        title: '处理状态',
        dataIndex: 'status',
        render: (text: any, record: any) => {
          return text == 0 ? '未处理' : text == 1 ? '处理中' : text == 2 ? '已处理' : '';
        }
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '详情',
              key: 'detail',
              auth: 'batteryFaultWarning_doDetail',
              onConfirm: () => {
                this.openDetailModal(record)
              },
            },
          ]
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        }
      },
    ]

    const tableProps = {
      columns,
      dataSource: list,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' }
    }

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'batteryFaultWarning/getFetchPage',
              url: '/battery/monitor/warning/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
            handleFieldsValue={this.dataFormat}
          />
        </Card>
        <Card className={styles.standardTable}>
          <PateoTable
            extraHandle={true}
            currentName={"page"}
            pageSizeName={"size"}
            tableProps={tableProps}
            fetchParams={{ type: 'batteryFaultWarning/getFetchPage', url: '/battery/monitor/warning/page' }}
            formValues={formValues}
          />
        </Card>
        <WarningDetail
          flag={detailFlag}
          param={currentDetailCode}
          modalVisible={detailModalVisible}
          closeModal={this.closeDetailModal}
        />
      </div>
    )
  }
}
export default connect(mapStateToProps)(BatteryFaultWarning);
